
// 邮件列表管理模块
const EmailListManager = {
    // 初始化邮件列表
    init: function() {
        const container = $('#email-list-wrapper');
        if (container.length) {
            // 添加邮件列表加载遮罩层
            if (!container.find('.local-loading-overlay').length) {
                container.append('<div class="local-loading-overlay" id="email-list-loading"><div class="local-loading-spinner"></div></div>');
            }
            
            // 绑定滚动加载更多
            container.on('scroll', () => {
                if (container.scrollTop() + container.innerHeight() >= container[0].scrollHeight - 5) {
                    this.loadEmailList(EmailModule.cache.currentFolder, EmailModule.cache.currentAccount, true);
                }
            });
        }

        // 绑定搜索按钮事件
        const searchBtn = $('#search-btn');
        if (searchBtn.length) {
            searchBtn.on('click', () => {
                this.updateSearchParams({
                    keyword: $('#keyword-search-input').val(),
                    sender: $('#sender-search-input').val()
                });
                this.reloadEmailList();
            });
        }

        // 绑定多选相关事件
        $('#select-all-emails').on('change', (event) => {
            const container = $('#email-list-container');
            if ($(event.target).is(':checked')) {
                container.addClass('multi-select-mode');
            }
            $('.email-item .email-checkbox').prop('checked', $(event.target).is(':checked'));
        });

        $('#multi-select-btn').on('click', () => {
            const container = $('#email-list-container');
            const isExiting = container.hasClass('multi-select-mode');
            
            container.toggleClass('multi-select-mode');

            if (isExiting) {
                $('#select-all-emails').prop('checked', false);
                $('.email-item .email-checkbox').prop('checked', false);
            }
        });

        // 绑定批量操作按钮
        $('#delete-selected-emails').on('click', () => this.deleteSelectedEmails());
        $('#mark-read-btn').on('click', () => this.markAsRead());
        $('#refresh-email-list').on('click', () => this.syncCurrentFolder());
    },

    // 缓存数据
    cache: {
        currentPage: 1,
        totalCount: 0,
        loadedCount: 0,
        hasMoreEmails: true,
        searchParams: {
            keyword: '',
            sender: '',
            startDate: '',
            endDate: '',
            hasAttachment: null,
            isRead: null
        }
    },
    
    isLoading: false,

    // 更新搜索条件
    updateSearchParams: function(params) {
        Object.assign(this.cache.searchParams, params);
    },

    // 清空搜索条件
    clearSearchParams: function() {
        this.cache.searchParams = {
            keyword: '',
            sender: '',
            startDate: '',
            endDate: '',
            hasAttachment: null,
            isRead: null
        };
        // 清空搜索输入框
        $('#keyword-search-input').val('');
        $('#sender-search-input').val('');
    },

    // 获取当前搜索条件
    getSearchParams: function() {
        return this.cache.searchParams;
    },

    // 检查是否有搜索条件
    hasSearchCondition: function() {
        const params = this.cache.searchParams;
        return !!(params.keyword || params.sender || params.startDate || 
                  params.endDate || params.hasAttachment !== null || params.isRead !== null);
    },

    // 重新加载邮件列表（使用缓存的搜索条件）
    reloadEmailList: function() {
        EmailModule.loadEmailList(EmailModule.cache.currentFolder, EmailModule.cache.currentAccount);
    },

    // 强制同步当前文件夹
    syncCurrentFolder: function() {
        const folder = EmailModule.cache.currentFolder;
        const accountId = EmailModule.cache.currentAccount;
        
        if (!folder || !accountId) {
            layui.layer.msg('请先选择一个文件夹', {icon: 7});
            return;
        }
        
        // 调用 loadEmailList 并设置 is_sync=true
        EmailModule.loadEmailList(folder, accountId, false, null, true);
    },

    // 构建邮件API请求
    buildEmailApiRequest: async function(folder, accountId, isSync = false) {
        let apiUrl;
        let params = new URLSearchParams({
            skip: (this.cache.currentPage - 1) * 50,
            limit: 50
        });

        // 添加 is_sync 参数
        if (isSync) {
            params.set('is_sync', 'true');
        }

        // 草稿箱使用专门的草稿接口
        if (folder === 'Drafts') {
            apiUrl = `/email-accounts/${accountId}/drafts?${params.toString()}`;
            return { apiUrl, totalCount: 0 };
        }

        // UNREAD虚拟文件夹：查询所有未读邮件（不限制文件夹）
        if (folder === 'UNREAD') {
            params.set('is_read', 'false');
        } else {
            // 如果有搜索条件，不限制文件夹，否则限制文件夹
            if (!this.hasSearchCondition()) {
                params.set('folder', folder);
            }
        }

        // 添加搜索条件
        const searchParams = this.getSearchParams();
        if (searchParams.keyword) {
            params.append('keyword', searchParams.keyword);
        }
        if (searchParams.sender) {
            params.append('sender', searchParams.sender);
        }
        // 预留其他搜索条件
        if (searchParams.isRead !== null) {
            params.set('is_read', searchParams.isRead.toString());
        }

        apiUrl = `/email-accounts/${accountId}/emails?${params.toString()}`;
        return { apiUrl, totalCount: 0 };
    },

    // 获取邮件数据
    fetchEmails: async function(apiUrl) {
        const response = await Api.apiRequest(apiUrl);
        const emails = response.data || response;
        const totalCount = response.count !== undefined ? response.count : 0;
        
        // 更新总数缓存
        if (this.cache.currentPage === 1) {
            this.cache.totalCount = totalCount;
        }
        
        return emails;
    },

    // 渲染邮件列表组件
    renderEmailListComponent: function(emails, append) {
        const container = $('#email-list-wrapper');
        
        if (!append) {
            // 保存遮罩层元素
            const loadingOverlay = container.find('.local-loading-overlay').detach();
            container.html('');
            if (loadingOverlay.length) {
                container.append(loadingOverlay);
            }
        }
        
        if (!emails || emails.length === 0) {
            if (!append) {
                this.renderEmptyPlaceholder(container);
            } else {
                // 移除之前可能显示的"没有更多"提示
                container.find('.no-more-emails-tip').remove();
                this.renderNoMoreTip(container);
            }
            return;
        }

        container.removeClass('is-empty');
        this.cache.loadedCount += emails.length;
        
        // 渲染邮件项
        this.renderEmailList(emails, append);
        
        // 判断是否还有更多邮件
        const hasMore = emails.length >= 50;
        
        // 更新标志
        this.cache.hasMoreEmails = hasMore;
        
        if (!hasMore) {
            // 没有更多邮件了，显示提示
            if (this.cache.loadedCount > 0) {
                this.renderNoMoreTip(container);
            }
        }
        
        // 页码总是+1
        this.cache.currentPage++;
    },

    // 渲染空占位符
    renderEmptyPlaceholder: function(container) {
        container.html('<div class="empty-placeholder">暂无邮件</div>');
        container.addClass('is-empty');
        if (!container.find('.local-loading-overlay').length) {
            container.append('<div class="local-loading-overlay" id="email-list-loading"><div class="local-loading-spinner"></div></div>');
        }
    },

    // 渲染"没有更多"提示
    renderNoMoreTip: function(container) {
        let noMoreTip = container.find('.no-more-emails-tip');
        if (!noMoreTip.length) {
            noMoreTip = $('<div class="no-more-emails-tip">没有更多邮件了</div>');
            container.append(noMoreTip);
        }
    },

    // 将新邮件插入到列表顶部（用于WebSocket实时推送）
    prependEmails: function(emails) {
        if (!emails || emails.length === 0) {
            return;
        }
        
        const container = $('#email-list-wrapper');
        if (!container.length) {
            console.error("错误: 未找到ID为 'email-list-wrapper' 的元素。");
            return;
        }
        
        // 移除空占位符（如果存在）
        container.find('.empty-placeholder').remove();
        container.removeClass('is-empty');
        
        // 获取或创建邮件列表容器
        let emailList = container.find('.email-list');
        if (!emailList.length) {
            emailList = $('<div class="email-list"></div>');
            // 在遮罩层之前插入
            const loadingOverlay = container.find('.local-loading-overlay');
            if (loadingOverlay.length) {
                loadingOverlay.before(emailList);
            } else {
                container.append(emailList);
            }
        }
        
        // 反向遍历邮件数组，以保持正确的顺序（最新的在最上面）
        for (let i = emails.length - 1; i >= 0; i--) {
            const email = emails[i];
            
            // 检查邮件是否已存在（避免重复）
            const existingItem = emailList.find(`.email-item[data-email-id="${email.id}"]`);
            if (existingItem.length > 0) {
                continue;
            }
            
            // 创建邮件项DOM元素
            const item = this.createEmailItemElement(email);
            
            // 插入到列表顶部，并添加动画效果
            item.css({
                opacity: 0,
                transform: 'translateY(-20px)'
            });
            
            emailList.prepend(item);
            
            // 触发动画
            setTimeout(() => {
                item.css({
                    transition: 'all 0.3s ease',
                    opacity: 1,
                    transform: 'translateY(0)'
                });
            }, 10);
        }
        
        // 重新渲染LayUI表单元素（复选框）
        layui.form.render('checkbox');
    },

    // 渲染邮件列表
    renderEmailList: function(emails, append) {
        const container = $('#email-list-wrapper');
        if (!container.length) {
            console.error("错误: 未找到ID为 'email-list-wrapper' 的元素。");
            return;
        }

        if (!append) {
            // 保存遮罩层元素
            const loadingOverlay = container.find('.local-loading-overlay').detach();
            // Clear the container only if it's a fresh load
            container.html('');
            // 重新添加遮罩层
            if (loadingOverlay.length) {
                container.append(loadingOverlay);
            }
        }

        if (!emails || emails.length === 0) {
            if (!append) {
                container.html('<div class="empty-placeholder">暂无邮件</div>');
                container.addClass('is-empty');
                // 确保遮罩层仍然存在
                if (!container.find('.local-loading-overlay').length) {
                    container.append('<div class="local-loading-overlay" id="email-list-loading"><div class="local-loading-spinner"></div></div>');
                }
            }
            return;
        }

        container.removeClass('is-empty');
        let emailList = container.find('.email-list');
        if (!emailList.length) {
            emailList = $('<div class="email-list"></div>');
            container.append(emailList);
        }

        emails.forEach(email => {
            // 使用提取的方法创建邮件项
            const item = this.createEmailItemElement(email);
            emailList.append(item);
        });

        // Re-render checkboxes for LayUI
        layui.form.render('checkbox');
    },

    // 获取选中的邮件ID列表
    getSelectedEmailIds: function() {
        return $('.email-item .email-checkbox:checked').map(function() {
            return parseInt($(this).data('email-id'));
        }).get();
    },

    // 退出多选模式
    exitMultiSelectMode: function() {
        const container = $('#email-list-container');
        // 移除多选模式class
        container.removeClass('multi-select-mode');
        // 取消所有复选框的选中状态
        $('#select-all-emails').prop('checked', false);
        $('.email-item .email-checkbox').prop('checked', false);
    },

    // 删除选中的邮件 - 复用统一方法
    deleteSelectedEmails: function() {
        const selectedIds = this.getSelectedEmailIds();
        if (selectedIds.length === 0) {
            layui.layer.msg('请先选择邮件');
            return;
        }

        // 如果是草稿箱，则调用彻底删除
        if (EmailModule.cache.currentFolder === 'Drafts') {
            EmailOperationsManager.permanentDeleteSelectedEmails();
            return;
        }

        // 调用统一的批量删除方法
        EmailOperationsManager.deleteSelectedEmails();
    },

    // 标记为已读
    markAsRead: async function() {
        const selectedIds = this.getSelectedEmailIds();
        const loadingIndex = layui.layer.load(1, { shade: [0.3, '#FFF'] });
        
        if (selectedIds.length > 0) {
            // Mark selected as read
            try {
                await Api.apiRequest(`/email-accounts/${EmailModule.cache.currentAccount}/emails/mark-as-read`, {
                    method: 'POST',
                    body: JSON.stringify({ email_ids: selectedIds })
                });
                layui.layer.msg('标记成功');
                // Update UI directly
                selectedIds.forEach(id => {
                    $(`.email-item[data-email-id='${id}']`).removeClass('unread');
                });
                // 退出多选模式
                this.exitMultiSelectMode();
            } catch (error) {
                console.error('标记已读失败:', error);
                layui.layer.msg('标记失败');
            } finally {
                layui.layer.close(loadingIndex);
            }
        } else {
            // Mark all as read
            try {
                await Api.apiRequest(`/email-accounts/${EmailModule.cache.currentAccount}/emails/mark-all-as-read`, {
                    method: 'POST',
                    body: JSON.stringify({ folder: EmailModule.cache.currentFolder })
                });
                layui.layer.msg('全部标记成功');
                // Update UI directly
                $('.email-item.unread').removeClass('unread');
            } catch (error) {
                console.error('全部标记已读失败:', error);
                layui.layer.msg('全部标记失败');
            } finally {
                layui.layer.close(loadingIndex);
            }
        }
    },

    // 标记单封邮件为已读 - 复用统一方法
    markAsReadSingle: function(accountId, emailId) {
        EmailOperationsManager.markAsRead(accountId, emailId);
    },

    // 加载邮件列表（主入口）
    loadEmailList: async function(folder, accountId, append = false, targetElement, isSync = false) {
        if (EmailModule.isLoading) return;
        
        // 如果是追加模式且已经没有更多邮件了，直接返回
        if (append && !this.cache.hasMoreEmails) {
            return;
        }

        if (!append) {
            this.cache.currentPage = 1;
            EmailModule.cache.currentFolder = folder;
            EmailModule.cache.currentAccount = accountId;
            this.cache.hasMoreEmails = true;
            
            // 保存遮罩层并清空容器
            const container = $('#email-list-wrapper');
            const loadingOverlay = container.find('.local-loading-overlay').detach();
            loadingOverlay.addClass('active');
            container.html('');
            container.append(loadingOverlay);

            // 如果是切换文件夹，则清空搜索条件
            if (targetElement) {
                this.clearSearchParams();
            }

            // 保存最后打开的文件夹
            localStorage.setItem('lastOpenedFolder', JSON.stringify({ accountId, folder }));

            // 移除所有文件夹的选中状态
            $('#account-folder-list .folder-item').removeClass('selected');
            
            // 为当前文件夹添加选中状态
            if (targetElement) {
                $(targetElement).closest('.folder-item').addClass('selected');
            } else {
                const folderLink = $(`a[data-account-id='${accountId}'][data-folder-name='${folder}']`);
                if (folderLink.length) {
                    folderLink.closest('.folder-item').addClass('selected');
                }
            }
        }

        // 根据文件夹调整按钮可见性
        const isSpecialFolder = ['Drafts', 'Sent'].includes(folder);
        $('#delete-selected-emails').toggle(!isSpecialFolder);
        $('#move-selected-emails').toggle(!isSpecialFolder);
        $('#permanent-delete-selected-emails').show();

        EmailModule.isLoading = true;

        // 如果是强制同步，显示加载动画
        const $refreshBtn = $('#refresh-email-list');
        const $icon = $refreshBtn.find('i');
        if (isSync) {
            $refreshBtn.addClass('syncing');
            $icon.addClass('layui-anim layui-anim-rotate layui-anim-loop');
        }

        try {
            // 构建API URL和参数
            const { apiUrl, totalCount } = await this.buildEmailApiRequest(folder, accountId, isSync);
            const emails = await this.fetchEmails(apiUrl);
            
            // 更新总数
            if (!append) {
                this.cache.totalCount = totalCount;
                this.cache.loadedCount = 0;
            }
            
            // 渲染邮件列表
            this.renderEmailListComponent(emails, append);
            
        } catch (error) {
            console.error('加载邮件列表失败:', error);
            layui.layer.msg('加载邮件列表失败', {icon: 2});
        } finally {
            EmailModule.isLoading = false;
            $('#email-list-loading').removeClass('active');

            if (isSync) {
                setTimeout(() => {
                    $refreshBtn.removeClass('syncing');
                    $icon.removeClass('layui-anim layui-anim-rotate layui-anim-loop');
                }, 500);
            }
        }
    },

    // 创建邮件项DOM元素
    createEmailItemElement: function(email) {
        const isSpecialFolder = ['Drafts', 'Sent'].includes(EmailModule.cache.currentFolder);
        const unreadClass = (isSpecialFolder || email.is_read) ? '' : 'unread';
        
        const item = $('<div></div>')
            .addClass(`email-item ${unreadClass}`)
            .attr('data-email-id', email.id)
            .data('email-folders', JSON.stringify(email.folders || []));
        
        // 草稿箱显示逻辑
        if (EmailModule.cache.currentFolder === 'Drafts') {
            const escapedRecipients = escapeHtml(email.recipients || '(无收件人)');
            const escapedSubject = escapeHtml(email.subject || '无主题');
            const attachmentInfo = email.attachment_count > 0 ? `(${email.attachment_count}个附件) ` : '';
            const saveTime = email.updated_at ? formatTimeAgo(new Date(email.updated_at)) : '';
            
            let actionsHtml = '<div class="layui-btn-group">';
            actionsHtml += `<button class="layui-btn layui-btn-primary layui-btn-xs" onclick="event.stopPropagation(); EmailOperationsManager.permanentDeleteEmail(${email.email_account_id}, ${email.id});" title="彻底删除"><i class="layui-icon layui-icon-close-fill"></i></button>`;
            actionsHtml += '</div>';
            
            item.html(`
                <div class="delete-layer">
                    <span class="delete-content">
                        <i class="layui-icon layui-icon-delete"></i> 删除
                    </span>
                </div>
                <div class="email-item-inner">
                    <div class="email-checkbox-wrapper">
                        <input type="checkbox" class="email-checkbox" data-email-id="${email.id}" lay-skin="primary">
                    </div>
                    <div class="email-content" onclick="EmailDetailsManager.viewEmail(${email.email_account_id}, ${email.id}, this)">
                        <div class="email-sender">${escapedRecipients}</div>
                        <div class="email-subject" title="${escapedSubject}">${escapedSubject}</div>
                        <div class="email-preview">${attachmentInfo}${saveTime}</div>
                    </div>
                    <div class="email-item-actions">
                        ${actionsHtml}
                    </div>
                </div>
            `);
        } else {
            // 正常邮件显示逻辑
            const escapedSender = formatSender(email.sender);
            const escapedSubject = escapeHtml(email.subject);
            const escapedPreview = escapeHtml(email.summary || '');

            // 生成文件夹标签HTML
            let folderTagsHtml = '';
            if (email.folders && email.folders.length > 1) {
                folderTagsHtml = '<div class="email-folders-tags">';
                email.folders.forEach(folderName => {
                    folderTagsHtml += `<span class="folder-tag">${escapeHtml(folderName)}</span>`;
                });
                folderTagsHtml += '</div>';
            }

            let actionsHtml = '<div class="layui-btn-group">';
            if (!isSpecialFolder) {
                actionsHtml += `<button class="layui-btn layui-btn-primary layui-btn-xs" onclick="event.stopPropagation(); EmailOperationsManager.moveEmail(${email.email_account_id}, ${email.id}, '${EmailModule.cache.currentFolder}');" title="移动"><i class="layui-icon layui-icon-export"></i></button>`;
                actionsHtml += `<button class="layui-btn layui-btn-primary layui-btn-xs" onclick="event.stopPropagation(); EmailOperationsManager.deleteEmail(${email.email_account_id}, ${email.id});" title="删除"><i class="layui-icon layui-icon-delete"></i></button>`;
            }
            actionsHtml += `<button class="layui-btn layui-btn-primary layui-btn-xs" onclick="event.stopPropagation(); EmailOperationsManager.permanentDeleteEmail(${email.email_account_id}, ${email.id});" title="彻底删除"><i class="layui-icon layui-icon-close-fill"></i></button>`;
            actionsHtml += '</div>';

            item.html(`
                <div class="delete-layer">
                    <span class="delete-content">
                        <i class="layui-icon layui-icon-delete"></i> 删除
                    </span>
                </div>
                <div class="email-item-inner">
                    <div class="email-checkbox-wrapper">
                        <input type="checkbox" class="email-checkbox" data-email-id="${email.id}" lay-skin="primary">
                    </div>
                    <div class="email-content" onclick="EmailDetailsManager.viewEmail(${email.email_account_id}, ${email.id}, this)">
                        <div class="email-sender">${escapedSender}</div>
                        <div class="email-subject" title="${escapedSubject}">${escapedSubject}</div>
                        ${folderTagsHtml}
                        <div class="email-preview" title="${escapedPreview}">${escapedPreview}</div>
                    </div>
                    <div class="email-item-actions">
                        ${actionsHtml}
                    </div>
                </div>
            `);
            
            item.attr('data-email-folders', JSON.stringify(email.folders || []));
        }
        
        return item;
    },

    // 格式化树形数据
    formatTreeData: function(nodes) {
        if (!nodes || nodes.length === 0) {
            return [];
        }
        const treeData = [];
        nodes.forEach(node => {
            if (!(['UNREAD', 'Drafts', 'Sent'].find(f => f === node.name))) {
                const newNode = {
                    title: node.display_name,
                    id: node.name,
                };
                if (node.children && node.children.length > 0) {
                    newNode.children = this.formatTreeData(node.children);
                }
                treeData.push(newNode);
            }
        });
        return treeData;
    }
};
